package com.zsrd.system.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zsrd.core.response.ResponseSupport;
import com.zsrd.system.domain.SysDict;
import com.zsrd.system.domain.dto.SysDictDto;
import com.zsrd.system.service.SysDictService;
import com.zsrd.system.service.impl.UserListener;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

@RestController
@RequestMapping("/system/dictManage")
public class SysDictController {

    @Autowired
    private SysDictService sysDictService;

    @RequestMapping(value = "query", method = RequestMethod.POST)
    public ResponseSupport query(@RequestBody SysDict sysDict) {
        List<Map> sysDict1 = sysDictService.selectByType(sysDict);
        return ResponseSupport.success(sysDict1);
    }

    @RequestMapping(value = "list", method = RequestMethod.POST)
    public ResponseSupport list(@RequestBody SysDict sysDict) {
        IPage<SysDict> list = sysDictService.selectAll(sysDict);
        return ResponseSupport.success(list);
    }

    /**
     * 新增和编辑
     *
     * @param sysDict
     * @return
     */
    @RequestMapping(value = "saveOrUpdate", method = RequestMethod.POST)
    public ResponseSupport saveOrUpdate(@RequestBody SysDict sysDict) {
        // 新增不传id
        if (sysDict.getId() == 0) {
            sysDictService.save(sysDict);
            // 编辑传id
        } else {
            sysDictService.updateById(sysDict);
        }
        return ResponseSupport.success("成功");
    }

    /**
     * 删除
     *
     * @param sysDict
     * @return
     */
    @RequestMapping(value = "remove", method = RequestMethod.POST)
    public ResponseSupport remove(@RequestBody SysDict sysDict) {
        boolean b = sysDictService.removeById(sysDict.getId());
        return ResponseSupport.success(b);
    }

//    /**
//     * 下载dict excel模板文件
//     *
//     * @param response
//     * @return
//     */
//    @RequestMapping(value = "/importExcel/downloadModel", method = RequestMethod.GET)
//    public void downloadModel(HttpServletResponse response) {
//        OutputStream outStream = null;
//        try {
//            org.springframework.core.io.Resource resource = new ClassPathResource("template/字典表模板.xlsx");
//            InputStream is = resource.getInputStream();
//            XSSFWorkbook workbook = new XSSFWorkbook(is);
//            response.reset();
//            response.setContentType("application/vnd.ms-excel");
//            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("字典表模板", "UTF-8") + ".xlsx");
//            outStream = response.getOutputStream();
//            workbook.write(outStream);
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            if (outStream != null) {
//                try {
//                    outStream.flush();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                try {
//                    outStream.close();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//    }


    /**
     * 设置响应结果
     *
     * @param response    响应结果对象
     * @param rawFileName 文件名
     * @throws UnsupportedEncodingException 不支持编码异常
     */
    private void setExcelResponseProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        //设置内容类型
        response.setContentType("application/vnd.vnd.ms-excel");
        //设置编码格式
        response.setCharacterEncoding("utf-8");
        //设置导出文件名称（避免乱码）
        String fileName = URLEncoder.encode(rawFileName.concat(".xlsx"), "UTF-8");
        // 设置响应头
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
    }

    private Date getBirthday(int year, int month, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, day);
        return calendar.getTime();
    }

    /**
     * 导出数据  加一列
     */
    @GetMapping("/export")
    public void exportUserExcel(HttpServletResponse response) throws IOException {
        OutputStream outputStream = response.getOutputStream();
        try {
            this.setExcelResponseProp(response, "字典列表");
            // 模拟根据条件在数据库查询数据
            List<SysDictDto> userList = sysDictService.listAll();
            //这个实现方式非常简单直接，使用EasyExcel的write方法将查询到的数据进行处理，以流的形式写出即可
            EasyExcel.write(outputStream, SysDictDto.class)//对应的导出实体类
                    .excelType(ExcelTypeEnum.XLSX)//excel文件类型，包括CSV、XLS、XLSX
                    .sheet("字典列表")//导出sheet页名称
                    .doWrite(userList); //查询获取的数据集合List<T>，转成excel
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            outputStream.flush();
            outputStream.close();
        }
    }


    /**
     * 导入数据
     */
    @PostMapping(value = "/importData")
    public void importData(MultipartFile file) {
        try {
            //获取文件的输入流
            InputStream inputStream = file.getInputStream();
            List<SysDictDto> lst = EasyExcel.read(inputStream) //调用read方法
                    //注册自定义监听器，字段校验可以在监听器内实现
                    .registerReadListener(new UserListener())
                    .head(SysDictDto.class) //对应导入的实体类
                    .sheet(0) //导入数据的sheet页编号，0代表第一个sheet页，如果不填，则会导入所有sheet页的数据
                    .headRowNumber(1) //列表头行数，1代表列表头有1行，第二行开始为数据行
                    .doReadSync(); //开始读Excel，返回一个List<T>集合，继续后续入库操作
            //导入数据库操作
            for (SysDictDto sysDictDto : lst) {
                sysDictService.insert(sysDictDto);
            }
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }

    /**
     * 下载模板
     */
    @GetMapping("/downloadModel")
    public void downloadModel(HttpServletResponse response) throws IOException {
        OutputStream outputStream = response.getOutputStream();
        try {
            this.setExcelResponseProp(response, "字典列表");
            // 创建表头
            List<SysDictDto> userList = new ArrayList<>();
            //这个实现方式非常简单直接，使用EasyExcel的write方法将查询到的数据进行处理，以流的形式写出即可
            EasyExcel.write(outputStream, SysDictDto.class)//对应的导出实体类
                    .excelType(ExcelTypeEnum.XLSX)//excel文件类型，包括CSV、XLS、XLSX
                    .sheet("字典列表")//导出sheet页名称
                    .doWrite(userList); //查询获取的数据集合List<T>，转成excel
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            outputStream.flush();
            outputStream.close();
        }
    }

}








